<?php

namespace app\utils;

use think\console\command\optimize\Schema;
use think\exception\HttpResponseException;
use think\facade\Config;
use think\facade\Lang;
use think\Response;

/**
 * Json输出类
 * Class Json
 * @package crmeb\utils
 */
class Json
{
    private $code = 200;

    public function code(int $code): self
    {
        $this->code = $code;
        return $this;
    }

    public function make(int $code, string $msg, ?array $data = null): Response
    {
        $request = app()->request;
        $res = compact('code', 'msg');

        if (!is_null($data))
            $res['data'] = $data;

        if ($res['msg'] && !is_numeric($res['msg'])) {
            if (!$range = $request->get('lang')) {
                $range = $request->cookie(Config::get('lang.cookie_var'));
            }
            $res['msg'] = Lang::get($res['msg'], [], $range !== 'deleted' && $range ? $range : 'zh-cn');
        }
        return Response::create($res, 'json', $this->code);
    }

    public function success($msg = 'ok', ?array $data = null): Response
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg = 'ok';
        }

        return $this->make(200, $msg, $data);
    }


    public function status($code, $msg, $result = [])
    {
        $code = strtoupper($code);
        if (is_array($msg)) {
            $result = $msg;
            $msg = 'ok';
        }
        return $this->success($msg, compact('code', 'result'));
    }

    public function successful($data, $msg='请求成功！', $code = 200)
    {
        return json(['code' => $code, 'msg' => $msg, 'data' => $data,'time' => time()]);
    }

    public function fail($msg = '请求失败！', ?array $data = null): Response
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg = 'ok';
        }
        return $this->make(400, $msg, $data);
    }
//    public function fail($data, $msg='fail', $code = 400)
//    {
//        return json(['code' => $code, 'msg' => $msg, 'data' => $data]);
//    }


}
